using System;
using System.Web;
using System.Web.Mvc;
using MvcContrib;
using DecisionMaking.BusinessLogic;
using DecisionMaking.BusinessLogic.Model;

namespace DecisionMaking.WebApp.Controllers
{
	/// <summary>
	/// Responsible for Environment management operations
	/// </summary>
	[HandleError]
    [Authorize]
    public class EnvironmentsController : BaseController
	{
		/// <summary>
		/// Injected by Windsor 
		/// </summary>
		public IEnvironmentManager EnvironmentManager {private get; set;}

		[HttpGet]
		public ActionResult Index() // environment list
		{
			ViewData["environments"] = EnvironmentManager.GetEnvironments(CurrentAccount.Id);
			return View("List");
		}
		
		[HttpGet]
		public ActionResult Add()
		{
			return View("Edit");
		}
		
		[HttpPost]
		public ActionResult Add(EnvironmentModel model)
		{
            if (ModelState.IsValid)
            {
                try
                {
                    model.AccountId = CurrentAccount.Id;
                    var environment = EnvironmentManager.SaveEnvironment(model);
                    // go to edit cue attributes
                    return this.RedirectToAction<CueAttributesController>(c => c.List(environment.Id));
                }
                catch (DuplicateEnvironmentNameException e)
                {
                    ModelState.AddModelError("Name", "An environment with this name already exists");

                }
            }

		    return View("Edit", model);

		}		
		
		[HttpGet]
		public ActionResult Edit(int id)
		{
			try
			{
				var environment = EnvironmentManager.GetEnvironment(id);

                // make sure current user is owner of current cue
                if (!environment.Account.Equals(CurrentAccount))
                {
                    return AccessDenied();
                }
				
				var model = new EnvironmentModel
				{
					Id = environment.Id,
					Name = environment.Name,
					Description = environment.Description,
					IndependentVariable = environment.IndependentVariableName,
					IsPublic = environment.Settings.IsPublic
				};
					
				return View(model);
			} 
			catch (EntityNotFoundException e)
			{
				return NotFound(e);
			}
		}	
		
		[HttpPost]
		public ActionResult Edit(EnvironmentModel model)
		{
		    if (ModelState.IsValid)
		    {
		        try
		        {
		            model.AccountId = CurrentAccount.Id;
		            var environment = EnvironmentManager.SaveEnvironment(model);
		            // go to list
		            return this.RedirectToAction(c => c.Index());				
		        }
		        catch (DuplicateEnvironmentNameException e)
		        {
		            ModelState.AddModelError("Name", "An environment with this name already exists");
				
		        }
		        catch (AccessDeniedException e)
		        {
		            return AccessDenied(e);
		        }
		        catch (EntityNotFoundException e)
		        {
		            return NotFound(e);
		        }
		    }
			
			return View(model);
		}	

        [HttpGet]
        public ActionResult Import()
        {
            return View();
        }

        /// <summary>
        /// Handles a CSV file import scenario
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Import(HttpPostedFileBase file)
        {
            try
            {
                var environment = EnvironmentManager.ImportCsv(CurrentAccount.Id, file.InputStream);

                // go to generate agents
                return this.RedirectToAction<AgentsController>(c => c.List(environment.Id));	
            }
            catch (DuplicateEnvironmentNameException e)
            {
                ModelState.AddModelError("File", e.Message);
            }
            catch (DuplicateCueNameException e)
            {
                ModelState.AddModelError("File", e.Message);
            }
            catch (DuplicateCandidateNameException e)
            {
                ModelState.AddModelError("File", e.Message);
            }
            catch (InvalidCueValueException e)
            {
                ModelState.AddModelError("File", e.Message);
            }

            return View();

        }
	}
}

